//
//  SWUserAcountViewModel.swift
//  SinaWeibo
//
//  Created by wszyxc on 16/7/22.
//  Copyright © 2016年 wszyxc. All rights reserved.
//

import UIKit

class SWUserAcountViewModel: NSObject {
    
    var userAcountModel:SWUserAcountModel?
    
    let file = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.plist")
    
    
    //提供一个单例给外界进行操作访问
    
    static let sharedUserAcountViewModel:SWUserAcountViewModel = SWUserAcountViewModel()
    
    override init() {
        
        super.init()
        userAcountModel = getUserAcount()
        
    }
    
    
    //使用accesToken
    
    var accesToken:String?{
        
        //如果有accesToken
        if userAcountModel?.access_token != nil{
            //看是否过期
            //当前保存的日期与当前日期对比
            
            if userAcountModel?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
                
                return userAcountModel?.access_token
            }else{
                return nil
            }
            
            
        }else{
            
            return nil
        }
        
        
    }
    
    //定义一个登陆的标识
    
    var isLogin:Bool{
        
        //根据accesToken来判断是否登陆
        return  accesToken != nil
    }
    
    
    

    //归档和解档
    
    func saveUserAcount(userAcountModel: SWUserAcountModel){
        
        self.userAcountModel = userAcountModel
        
        NSKeyedArchiver.archiveRootObject(userAcountModel, toFile: file)
        
        
    }
    
    func getUserAcount()->SWUserAcountModel?{
   
       return  NSKeyedUnarchiver.unarchiveObjectWithFile(file) as? SWUserAcountModel
        
    }
    
    
}
    // MARK: - 请求oAthor界面的数据
    
extension SWUserAcountViewModel{
     
        //用code 请求 userAccount
        func loadUserAcount(code:String,finished:(isSuccess:Bool)->()){
            
            
            let urlStr = "https://api.weibo.com/oauth2/access_token"
            
            let params = [
                
                "client_id": APPKEY,
                "client_secret": APPSECRET,
                "grant_type": "authorization_code",
                "code": code,
                "redirect_uri": APPREDIRECT_URI
            ]
            
            
            
           NetWorkTools.sharedNetWorkTools.request(.Post, URLString: urlStr, parameters: params) { (responseObject, error) -> () in
                
                //如果 错误信息有值 直接返回
                if error != nil{
                    
                    print(error)
                    
                    return
                }
                
                //如果有响应值,且响应值能够转化为字典
                guard let dict = responseObject as? [String: AnyObject] else{
                    
                    print("后台返回格式不对")
                    finished(isSuccess: false)
                    return
                }
                
                
                //字典转模型
                
                let account = SWUserAcountModel(dict: dict)
                
             //   print("account----\(account)")
                //获取个人信息
                self.loadUserInfo(account, finished: { (isSuccess) -> () in
                    
                    print("请求完个人信息")
                    
                })
                
            }
            
        }
        
        
        //获取个人信息
        
        func loadUserInfo(account:SWUserAcountModel,finished:(isSuccess:Bool)->()){
            
            // 请求地址
            let urlString = "https://api.weibo.com/2/users/show.json"
            
            // 请求参数
            let params = [
                "access_token": account.access_token ?? "",
                "uid": account.uid ?? ""
            ]
            
            NetWorkTools.sharedNetWorkTools.request(.Get, URLString: urlString, parameters: params) { (responseObject, error) -> () in
                
                print("获取到个人信息")
                //    print(responseObject)
                
                //判断错误信息
                if error != nil{
                    
                    print(error)
                    
                    return
                }
                
                //判断返回值是否是字典
                guard let dict = responseObject as? [String:AnyObject] else{
                    
                    print("服务器返回的用户信息数据不对")
                    
                    return
                }
                //向模型中添加用户信息
                account.name = dict["name"] as? String
                account.avatar_large = dict["avatar_large"] as? String
                
                //归档
                
                
                NSKeyedArchiver.archiveRootObject(account, toFile: self.file)
                
              //  print(account)
            }
            
            
        }

    }
    




